/**
 * 
 */
package hu.gbalage.owlforms.xforms;

import hu.gbalage.owlforms.api.data.FormData;
import hu.gbalage.owlforms.xforms.gen.FormDataParser;
import hu.gbalage.owlforms.xforms.work.Boot;
import hu.gbalage.owlforms.xforms.xhtml.XHTMLBase;

import java.io.IOException;
import java.io.PrintStream;
import java.net.URI;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

/**
 * @author balage
 *
 */
public class SaveFormData implements HttpHandler {

	/* (non-Javadoc)
	 * @see com.sun.net.httpserver.HttpHandler#handle(com.sun.net.httpserver.HttpExchange)
	 */
	@Override
	public void handle(HttpExchange arg0) throws IOException {
		
		try{
			
		
		Document doc = XMLHelper.parse(arg0.getRequestBody());

		FormData data = FormDataParser.parse(doc);
		
		URI instance = data.getURI();
		
		Boot.save(data);
		
		//FormData loaded = Boot.manager.load(data.getForm(), instance);
		
		
		XHTMLBase xdoc = new XHTMLBase("Mentve");
		/* 
		
		FormDataPrinter printer = new FormDataPrinter();
		
		xdoc.body.appendChild(printer.toXHTML(xdoc.doc, loaded));
		
		*/
		
		Element a = xdoc.doc.createElement("xhtml:a");
		a.setAttribute("href", "test?uri="+instance.getFragment());
		a.setTextContent(instance.toString());
		xdoc.body.appendChild(a);
		
		arg0.sendResponseHeaders(200, 0);
		
		XMLHelper.serialize(xdoc.doc, arg0.getResponseBody());
		
		
		
		}catch(Exception e){
			e.printStackTrace();
			arg0.sendResponseHeaders(500, 0);
			PrintStream p = new PrintStream(arg0.getResponseBody());
			e.printStackTrace(p);
			
		}finally{
			arg0.close();
		}
	}

}
